#coding=utf-8


def auth(func):
    def inner(*args,**kw):
        print 'first run %s!'%func.__name__
        funcs = func(*args, **kw)
        print 'after run %s!'%func.__name__
        return funcs
    return inner


@auth
def f1( *args,**kw):
    print 'run f1 %s' %(args)


@auth
def f2( *args,**kw):
    #print 'run f1 %s' %(args)
    return args


f1(['sfa','saffsa'])
print f2(['f2'])

#带参数的装饰器,原理 两层调用
def auth_param(param):
    def outter(func):
        def inner(*args,**kwargs):
            print 'first run %s brefore %s!'%(func.__name__,param)
            funcs = func(*args, **kwargs)
            print 'after run %s brefore %s!'%(func.__name__,param)
            return funcs
        return inner
    return outter

@auth
def f3(*args,**kwargs):
    out = 'run f3 with %s'%args
    return out


@auth_param('decorate_params')
def f4(*args,**kwargs):
    out = 'run f4 with %s'%args
    return out

print f3('f3')
print f4('f4')

#多层装饰器,一层一层执行
@auth
@auth_param('decorate_params')
def f5(*args,**kwargs):
    out = 'run f5 with %s'%args
    return out

print f5('f5')


#看看更拽的装饰器
def before(request,kargs):
    print 'brfore'

def after(request,kargs):
    print 'after'

def deco_fun(before_func, after_func):
    def outer(func):
        def inner(request, kargs):
            before_resut = before_func(request,kargs)
            if before_resut !=None:
                return before_resut

            main_result = func(request,kargs)
            after_result = after_func(request,kargs)
            if after_result!=None:
                return after_result
            return main_result
        return inner
    return outer

@deco_fun(before, after)
def f6(request, kargs):
    return request

print f6('f6','haha')


